<template>
  <div class="container-box">
    <h3 class="">{{ params.id ? '编辑商品' : '新增商品' }}</h3>
    <el-form ref="dialogForm" class="form-box" :inline="true" :model="dialogForm" :rules="rules" label-width="120px" title="商品">
      <div class="form-btn-box">
        <el-button type="primary" size="mini" :loading="saving" @click="onSubmit('submit')">保存</el-button>
        <el-button type="default" size="mini" :loading="saving" @click="handleForm('cancel')">取消</el-button>
      </div>
      <el-tabs v-model="selTab" @tab-click="changeTab">
        <el-tab-pane label="基本信息" name="1">
          <!-- <el-form ref="dialogForm" :model="dialogForm" :rules="rules" label-width="120px"> -->
          <template v-for="(item, index) in dialogColums.filter(d => d.isForm)">
            <el-form-item v-if="item.key === 'cat_id'" :key="index" :label="item.title" :prop="item.key">
              <el-select v-model="dialogForm[item.key]" :placeholder="`请选择${item.title}`" style="width: 100%;">
                <el-option v-for="item in goodsCategory" :key="item.cat_id" :label="item.cat_name" :value="item.cat_id" />
              </el-select>
            </el-form-item>
            <el-form-item v-else :key="index" :label="item.title" :prop="item.key">
              <el-input v-if="item.type === 'number'" v-model.number="dialogForm[item.key]" :type="item.type" :placeholder="`请输入${item.title}`" />
              <el-input v-else v-model="dialogForm[item.key]" :type="item.type" :placeholder="`请输入${item.title}`" />
            </el-form-item>
          </template>
          <!-- </el-form> -->
          <div class="tip" style="color: #ff4949">提示： 辅助单位换算（基本单位）= 基本单位换算（辅助单位）</div>
          <div v-if="dialogForm.unit_name && dialogForm.unit_name2" class="tip" style="color: #ff4949">
            {{ dialogForm.unit_convert2 }}{{ dialogForm.unit_name }} = {{ dialogForm.unit_convert }}{{ dialogForm.unit_name2 }}
          </div>
        </el-tab-pane>
        <el-tab-pane label="商品规格" name="2">
          <div class="dialog-box">
            <el-row style="padding: 10px 0;">
              <el-radio-group v-model="goodsAttrType">
                <el-radio :label="1">单规格</el-radio>
                <el-radio :label="2">多规格</el-radio>
              </el-radio-group>
            </el-row>
            <template v-if="goodsAttrType===1">
              <!-- <el-table :data="" border v-if="attrData.length">
                <template v-for="(item, index) in attrColumns">
                  <el-table-column :prop="item.key" :label="item.title" :key="index">
                    <template slot-scope="scope">
                      <div class="" v-if="item.key === ''">{{scope.row[item.key]}}</div>
                      <div class="" v-else>{{handleRowResult(item, scope.row)}}</div>
                    </template>
                  </el-table-column>
                </template>
                <el-table-column label="操作">
                  <template slot-scope="{row, index}">
                    <el-button type="primary" @click="handleRowOption({row, index,}, 'del')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table> -->
            </template>

            <template v-if="goodsAttrType===2">
              <el-row style="marginBottom: 20px">
                <el-select v-model="selAttr" :placeholder="`请选择商品规格模版`" style="marginRight:20px">
                  <el-option v-for="item in goods_attr" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-button type="primary" :loading="saving" @click="handleAttrOp('add_attr_tem')">确认</el-button>
                <el-button type="default" :loading="saving" @click="handleAttrOp('goods_attr')">添加规格模板</el-button>
                <!-- <el-button type="primary" @click="generateAttr" :loading="saving">快速生成</el-button> -->
              </el-row>
              <div v-if="attrTem.length" class="attr-box">
                <div v-for="(item, index) in attrTem" :key="index" class="attr-wrap">
                  <div class="attr-label">{{ item.attr.label }}
                    <i class="el-icon-error icon" @click="handleAttrOp('del_attr', { 'temIndex': index })" />
                  </div>
                  <div v-if="item.attr_value.length" class="attr-value">
                    <!-- <div v-for="(detail, index) in item.attr_value" :key="index">
                    <div class="attr-value-item">{{detail.label}}</div>
                  </div> -->
                    <el-tag v-for="(tag, ti) in item.attr_value" :key="tag.name" class="attr-value-tag" closable @close="handleAttrOp('del_attr_item', { 'temIndex': index, 'vIndex': ti })">
                      {{ tag.label }}
                    </el-tag>
                    <el-input
                      v-if="item.showInput"
                      ref="saveTagInput"
                      v-model="newAttrValue"
                      class="add-attr-input"
                      :placeholder="`请输入新的${item.attr.label}规格`"
                      size="small"
                      clearable
                      @keyup.enter.native="handleAttrOp('add_attr_item', { 'temIndex': index })"
                      @blur="handleAttrOp('add_attr_item', { 'temIndex': index })"
                    />
                    <el-button v-else class="button-new-tag" size="small" @click="handleAttrOp('showInput', { temIndex: index, show: true })">添加新的{{ item.attr.label }}规格</el-button>
                  </div>
                  <div v-else>未获取 {{ item.attr.label }}-{{ item.attr.value }} 字典详情</div>
                </div>
              </div>
              <el-row v-if="attrTem.length" style="marginBottom: 10px">
                <el-button type="primary" icon="el-icon-plus" :loading="saving" @click="handleAttrOp('new_attr_tem')">添加新规格</el-button>
                <el-button type="success" :loading="saving" @click="generateAttr">快速生成</el-button>
                <el-button type="success" :loading="saving" @click="onSubmit">保存</el-button>
              </el-row>

              <el-table v-if="attrData.length" :data="attrData" border>
                <template v-for="(item, index) in attrColumns">
                  <el-table-column :key="index" :prop="item.key" :label="item.label">
                    <template slot-scope="scope">
                      <div class="">
                        <el-input v-model="scope.row[item.key]" :placeholder="`请输入${item.label}`" />
                      </div>
                      <!-- <div class="" v-else>{{handleRowResult(item, scope.row)}}</div> -->
                    </template>
                  </el-table-column>
                </template>
                <el-table-column label="操作">
                  <template slot-scope="{row, $index}">
                    <el-button type="primary" @click="handleRowOption({row, index: $index,}, 'del')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </div>
</template>

<script>
import { goodsDetail, goodsList, goodsAdd } from '../../api/goods'
export default {
  name: 'Goods',
  data() {
    var handleUnitConvert = (rule, value, callback) => {
      console.log('this.dialogForm==', this.dialogForm);
      const dialogForm = this.dialogForm;
      if (!dialogForm.unit_name2.trim()) {
        callback();
      }
      else if (!dialogForm.unit_convert2) {
        console.log('dialogForm.unit_convert2==', dialogForm.unit_convert2);
        callback(new Error('请输入辅助单位换算'));
      }
      else if (dialogForm.unit_convert > dialogForm.unit_convert2) {
        callback(new Error('辅助单位 比 基本单位大'));
      }
      else {
        callback();
      }
    };
    var attrColumns = [
      { label: '规格', key: 'sku', type: 'text', isFilter: true, isTable: true, isForm: true },
      { label: '售价', key: 'retail_price', type: 'text', isFilter: true, isTable: true, isForm: true },
      { label: '成本价', key: 'cost_price', type: 'text', isFilter: true, isTable: true, isForm: true },
      { label: '库存', key: 'stock', type: 'number', isFilter: true, isTable: true, isForm: true },
      { label: '重量(g)', key: 'weight', type: 'number', isFilter: true, isTable: true, isForm: true },
      { label: '产品编号', key: 'code', type: 'text', isFilter: true, isTable: true, isForm: true },
      { label: '排序', key: 'sort', type: 'text', isFilter: true, isTable: true, isForm: true }
    ];
    return {
      columns: [
        { title: '商品名称', key: 'goods_name', type: 'text', isFilter: true, isTable: true, isForm: true },
        { title: '商品全称', key: 'full_goods_name', type: 'text', isFilter: true, isTable: true, isForm: true },
        { title: '分类名称', key: 'cat_id', type: 'goodsCategoryDict', clearable: true, isFilter: true, isTable: true, isForm: true },
        { title: '排序', key: 'sort', type: 'number', sortable: true, isFilter: false, isTable: true, isForm: true },
        { title: '基本单位 & 辅助单位', key: 'unit_name', type: 'text', isFilter: false, isTable: true },
        { title: '基本 & 辅助单位换算', key: 'unit_convert', type: 'text', isFilter: false, isTable: true },
        { title: '基本单位', key: 'unit_name', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '辅助单位', key: 'unit_name2', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '基本单位换算', key: 'unit_convert', type: 'number', isFilter: false, isTable: false, isForm: true },
        { title: '辅助单位换算', key: 'unit_convert2', type: 'number', isFilter: false, isTable: false, isForm: true },
        { title: '库存', key: 'stock', type: 'text', isFilter: true, isTable: true }
      ],
      list: [],
      query: {},
      dict: {},

      saving: false,
      dialogVisible: false,
      dialogColums: [],

      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: ['change', 'blur'] }
          // { required: true, message: '分类名称已存在', validator: cateNameValidator }
        ],
        full_goods_name: [
          { required: true, message: '请输入商品全称', trigger: ['change', 'blur'] }
          // { required: true, message: '分类名称已存在', validator: cateNameValidator }
        ],
        cat_id: [{ required: true, message: '请输入分类名称', trigger: ['change', 'blur'] }],
        unit_name: [{ required: true, message: '请输入基本单位', trigger: ['change', 'blur'] }],
        unit_name2: [{ required: false, message: '请输入辅助单位', trigger: ['change', 'blur'] }],
        unit_convert: [{ required: true, message: '请输入基本单位换算', trigger: ['change', 'blur'] }],
        unit_convert2: [
          { required: false, message: '请输入辅助单位换算', trigger: ['change', 'blur'] },
          { required: false, validator: handleUnitConvert }
        ]
      },
      dialogForm: {
        goods_name: '捷时达995硅酮结构密封胶',
        full_goods_name: '捷时达995',
        cat_id: 77,
        sort: 500,
        unit_name: '支',
        unit_name2: '件',
        unit_convert: 1,
        unit_convert2: 20
      },
      goods_attr: [],
      goodsAttrDialogVisible: false,
      selGoods: {},
      dictDetails: {},

      selTab: '1',
      goodsAttrType: 1,
      selAttr: '',
      attrTem: [],
      attrColumns: attrColumns,
      attrData: [],
      newAttrValue: ''
    };
  },
  computed: {
    params() {
      return this.$route.params;
    },
    goodsCategory() {
      return this.$store.getters.category?.data || [];
    },
    goodsCategoryDict() {
      return this.$store.getters.goodsCategoryDict;
    },
    system() {
      const system = this.$store.state.system;
      console.log('goods--system==', system);
      this.dictDetails = system.dictDetails || {};
      this.goods_attr = system?.dictDetails?.goods_attr?.data || [];
      return system;
    }
    // goods_attr() {
    //   const goods_attr = this.system?.dictDetails?.goods_attr?.data || [];
    //   return goods_attr;
    // },
  },
  watch: {
    // TODO 过滤
    goodsAttrType: {
      handler(val) {
        // if (val === 1) {
        // }
      },
      immediate: true
    }
  },
  created() {
    this.dict.goodsCategoryDict = this.$store.getters.goodsCategoryDict;
    this.dialogColums = this.$json.cloneDeep(this.columns);

    this.getData();
    const { type, id } = this.params;
    if (type !== 'add') {
      this.getData2();
    }
  },
  methods: {
    // 保存
    onSubmit() {
      console.log('onSubmit--attrData==', this.attrData, this.dialogForm);
    },
    async getData2() {
      const { data } = await goodsDetail({ id: this.params?.id });
      // this.list = data?.list || [];
      console.log('getData2--data==', data);
    },
    async getData() {
      const { data } = await goodsList();
      this.list = data?.list || [];
      console.log('this.list==', this.list);
    },
    changeTab(value) {
      console.log('changeTab--value==', value);
    },
    // 处理table 显示；
    handleRowResult(item, row) {
      // console.log('handleRowResult--item', item, row);
      const value = row[item.key] || '';
      if (item.key === 'stock') {
        if (row.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
          const unitNum = row.stock % row.unit_convert2;
          const unitNum2 = Math.floor(row.stock / row.unit_convert2);
          return `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
        }
        return `${row.stock}${row.unit_name}`
      }
      if (item.key === 'cat_id') {
        const category = this.goodsCategoryDict[value]
        return category?.cat_name || value
      }
      if (item.key === 'unit_name') {
        return `${row.unit_name} / ${row.unit_name2 || '-'}`
      }
      if (item.key === 'unit_convert') {
        if (row.unit_name2) {
          return `${row.unit_convert2}${row.unit_name} = ${row.unit_convert}${row.unit_name2}`
        }
        return
      }
      return value;
    },
    // 操作事件；
    async handleRowOption({ row, index }, type) {
      console.log('handleRowOption--row==', row, index, type);
      if (type === 'del') {
        let isConfirm = false;
        try {
          isConfirm = await this.$confirm('确定要删除该规格吗？', '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' })
        } catch { }
        if (isConfirm) {
          this.attrData.splice(index, 1);
          this.$forceUpdate();
        }
      }
    },
    // dialog 提交；
    async onDialogConfirm() {
      let isValid = false;
      console.log('onDialogConfirm--this.$refs.dialogForm.==', this.$refs.dialogForm);
      this.$refs.dialogForm.validate(valid => {
        console.log('onDialogConfirm--valid==', valid);
        isValid = valid;
      })
      console.log('onDialogConfirm--this.saving ==', this.saving, isValid);
      if (this.saving) return this.$message.error('请勿重复提交');
      if (!isValid) return this.$message.error('请检查提交内容');

      this.saving = true;
      try {
        const payload = this.$json.cloneDeep(this.dialogForm);
        const { data } = await goodsAdd(payload);
        console.log('goodsAddCate==', data);
        if (data && data.length === 2) {
          if (data[1]) {
            this.getData();
            this.$message.success('添加成功')
            this.dialogVisible = false;
          } else {
            this.$message.error(`添加失败: ${payload.goods_name} ${payload.full_goods_name} 已存在`)
          }
        } else {
          this.$message.error(`异常：添加失败`)
        }
      } catch (e) {
        console.log('goodsAddCate--e==', e);
      }
      this.saving = false;
    },

    async handleAttrOp(type, data) {
      console.log('handleAttrOp==', type, data);
      if (type === 'add_attr_tem') {
        if (this.selAttr && this.attrTem.findIndex(d => d.attr.value === this.selAttr) < 0) {
          const attrTem = this.goods_attr.find(d => d.value === this.selAttr);
          this.attrTem.push({
            attr: attrTem,
            attr_value: this.$json.cloneDeep(this.dictDetails[this.selAttr])?.data || []
          })
          console.log('handleAttrOp--attrTem==', this.attrTem);
        }
      }
      else if (type === 'del_attr') {
        const { temIndex } = data;
        let isConfirm = false;
        try {
          isConfirm = await this.$confirm('确定要删除该规格吗？', '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' })
        } catch { }
        if (isConfirm) {
          this.attrTem.splice(temIndex, 1);
          this.$forceUpdate();
        }
        console.log('handleAttrOp--isConfirm==', isConfirm);
      }
      else if (type === 'del_attr_item') {
        const { temIndex, vIndex } = data;
        let isConfirm = false;
        try {
          isConfirm = await this.$confirm('确定要删除该规格吗？', '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' })
        } catch { }
        if (isConfirm) {
          this.attrTem[temIndex].attr_value.splice(vIndex, 1);
          this.$forceUpdate();
        }
      }
      else if (type === 'showInput') {
        const { temIndex } = data;
        this.attrTem[temIndex].showInput = true;
        this.$forceUpdate();
      }
      else if (type === 'add_attr_item') {
        const { temIndex } = data;
        if (this.newAttrValue) {
          console.log('this.attrTem[temIndex].attr_value.filter(d => d.label === this.newAttrValue).length==', this.attrTem[temIndex].attr_value.filter(d => d.label === this.newAttrValue).length);
          if (this.attrTem[temIndex].attr_value.findIndex(d => d.label === this.newAttrValue) < 0) {
            this.attrTem[temIndex].attr_value.push({
              name: this.newAttrValue,
              label: this.newAttrValue
            })
            this.newAttrValue = '';
          } else {
            this.$message.error(`${this.newAttrValue} 已存在`)
            return;
          }
        }
        this.attrTem[temIndex].showInput = false;
        console.log('this.attrTem==', this.attrTem);
        this.$forceUpdate();
      }
      else if (type === 'new_attr_tem') {

      }
      else if (type === 'generate_attr') {
      }
    },
    addAttrOp() {
      console.log('addAttr--this.selAttr==', this.selAttr, this.attrTem);
      // const attr = this.selAttr.attr;
      if (this.selAttr && this.attrTem.findIndex(d => d.attr.value === this.selAttr) < 0) {
        const attrTem = this.goods_attr.find(d => d.value === this.selAttr);
        this.attrTem.push({
          attr: attrTem,
          attr_value: this.$json.cloneDeep(this.dictDetails[this.selAttr])?.data || []
        })
        console.log('addAttr--attrTem==', this.attrTem);
      }
    },
    // 生成商品属性
    generateAttr() {
      const oldAttr = this.selGoods.attr;
      const attrObj = [];
      let columns = [];
      this.attrTem.forEach((d, i) => {
        attrObj[i] = d.attr_value.map(a => a.label);
        columns.push({ label: d.attr.label, key: d.attr.value, type: 'attr' })
      })
      columns = columns.concat(this.attrColumns)
      const data = this.getSku(attrObj);
      console.log('getSku--data==', data);

      const attrData = data.map((d, i) => {
        const sku = d.join(',');
        const obj = {
          socket: ''
        };
        d.forEach((v, vi) => {
          console.log('generateAttr--v==', i, vi, v);
          obj[columns[vi].key] = v;
        })
        return obj;
      })
      this.selGoods.attr = attrData;
      this.attrData = attrData;
      this.attrColumns = columns;
      console.log('generateAttr--this.attrColumns==', this.attrColumns);
      console.log('generateAttr--this.attrData==', this.attrData);
    },
    getSku(data) {
      console.log('getSku--data==', data);
      const newArr = [];
      // let delimiter = '';
      const delimiter = '|(_##sku##_)|'; // 分隔符，避免sku中出现相同字符出现数据丢失情况
      function get(index, arr, str) {
        let list = '';
        for (let i = 0; i < arr[index].length; i++) {
          list = (str === '' ? '' : str + delimiter) + arr[index][i];
          console.log('get--list==', index, list);
          if (index + 1 === arr.length) {
            newArr.push(list.split(delimiter));
          } else {
            get(index + 1, arr, list);
          }
        }
        return newArr;
      }
      return get(0, data, '');
    },
    delAttr(index) {
      console.log('delAttr--index==', index);
    },
    async onSubmit() {
      let isValid = false;
      console.log('onDialogConfirm--this.$refs.dialogForm.==', this.$refs.dialogForm);
      this.$refs.dialogForm.validate(valid => {
        console.log('onDialogConfirm--valid==', valid);
        isValid = valid;
      })
      console.log('onDialogConfirm--this.saving ==', this.saving, isValid);
      if (this.saving) return this.$message.error('请勿重复提交');
      if (!isValid) return this.$message.error('请检查提交内容');

      this.saving = true;
      try {
        const payload = this.$json.cloneDeep(this.dialogForm);
        const { data } = await goodsAdd(payload);
        console.log('goodsAddCate==', data);
        this.$message.success('添加成功')

        // if (data && data.length === 2) {
        //   if (data[1]) {
        //     this.getData();
        //     this.$message.success('添加成功')
        //     this.dialogVisible = false;
        //   } else {
        //     this.$message.error(`添加失败: ${payload.goods_name} ${payload.full_goods_name} 已存在`)
        //   }
        // } else {
        //   this.$message.error(`异常：添加失败`)
        // }
      } catch (e) {
        console.log('goodsAddCate--e==', e);
      }
      this.saving = false;
    }
  }
}

</script>
<style lang="scss" scoped>
.container-box {
  padding: 20px;
}
.form-box {
  position: relative;
}
.form-btn-box {
  position: absolute;
  right: 20px;
  z-index: 20;
}
.attr-box {
  .attr-wrap {
    margin-bottom: 20px;
    .attr-label {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 10px;
    }
    .attr-value {
      display: flex;
      flex-wrap: wrap;
      .attr-value-tag {
        margin-right: 10px;
      }
      .add-attr-input {
        width: 200px;
      }
    }
  }
}
.icon {
  cursor: pointer;
}
::v-deep .el-dialog.attr-dialog {
  color: red;
  .goods-name {
    font-size: 20px;
    font-weight: bold;
  }
}
</style>
